//
//  LRJ_TextAttachment.m
//  Pods
//
//  Created by imac_LRJ on 2022/6/7.
//

#import "LRJ_TextAttachment.h"
#import "LRJ_TextAttachment+bindAction.h"
#import "LRJ_CTLayoutRun.h"
// 组件插入到AttributedString中的Key标识
 NSString * const LRJ_TextAttachmentAttributeName = @"LRJ_TextAttachmentAttributeName";
// "\uFFFC"
 NSString * const LRJ_TextAttachmentReplacementCharacter = @"\uFFFC";


@interface LRJ_TextAttachment ()
@property (nonatomic, strong) NSMutableArray *callBacks;
@end


@implementation LRJ_TextAttachment
//实现协议中的属性
@synthesize type = _type, size = _size, edgeInsets = _edgeInsets, contents = _contents, position = _position, length = _length, baselineFontMetrics = _baselineFontMetrics;

- (instancetype)init
{
    self = [super init];
    if (self) {
        _retriveFontMetricsAutomatically = YES;
        _baselineFontMetrics = LRJ_FontMetricsZero;
        
        _edgeInsets = UIEdgeInsetsMake(0, 1, 0, 1);
        _userInfoPriority = 999;
        _eventPriority = 999;
        _callBacks = [NSMutableArray array];
    }
    return self;
}

+ (instancetype)textAttachmentWithContents:(id)contents type:(LRJ_AttachmentType)type size:(CGSize)size
{
    LRJ_TextAttachment *att = [[LRJ_TextAttachment alloc] init];
    att.contents = contents;
    att.type = type;
    att.size = size;
    
    return att;
}

- (UIEdgeInsets)edgeInsets
{
    //如果是自动适配模式
    if (_retriveFontMetricsAutomatically) {
        CGFloat lineHeight = LRJ_FontMetricsGetLineHeight(_baselineFontMetrics);
        CGFloat inset = (lineHeight - self.size.height) / 2;
        
        return UIEdgeInsetsMake(inset, _edgeInsets.left, inset, _edgeInsets.right);
    }
    
    return _edgeInsets;
}

- (CGSize)placeholderSize
{
    return CGSizeMake(self.size.width + self.edgeInsets.left + self.edgeInsets.right, self.size.height + self.edgeInsets.top + self.edgeInsets.bottom);
}

#pragma mark - Event

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents
{
    _target = target;
    _selector = action;
    
    _responseEvent = (_target && _selector) && [_target respondsToSelector:_selector];
}

- (void)registerClickBlock:(void (^)(void))callBack {
    if (!callBack) {
        return;
    }
    [_callBacks addObject:callBack];
}

- (void)handleEvent:(id)sender
{
    if (_target && _selector) {
        if ([_target respondsToSelector:_selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            [_target performSelector:_selector withObject:sender];
#pragma clang diagnostic pop
        }
    }
    if (_callBacks.count) {
        for (void (^callBack)(void) in _callBacks) {
            if (callBack) {
                callBack();
            }
        }
    }
}

@end


@implementation NSAttributedString (GTextAttachment)
//遍历方法，取出所有的文本附件信息，与range
- (void)wmg_enumerateTextAttachmentsWithBlock:(void (^)(LRJ_TextAttachment *, NSRange, BOOL *))block
{
    [self wmg_enumerateTextAttachmentsWithOptions:0 block:block];
}

- (void)wmg_enumerateTextAttachmentsWithOptions:(NSAttributedStringEnumerationOptions)options block:(void (^)(LRJ_TextAttachment *, NSRange, BOOL *))block
{
    if (!block) return;
    
    [self enumerateAttribute:LRJ_TextAttachmentAttributeName inRange:NSMakeRange(0, self.length) options:options usingBlock:^(LRJ_TextAttachment * attachment, NSRange range, BOOL *stop) {
        if (attachment && [attachment isKindOfClass:[LRJ_TextAttachment class]]) {
            block(attachment, range, stop);
        }
    }];
}

+ (instancetype)wmg_attributedStringWithTextAttachment:(LRJ_TextAttachment *)attachment
{
    return [self wmg_attributedStringWithTextAttachment:attachment attributes:@{}];
}

+ (instancetype)wmg_attributedStringWithTextAttachment:(LRJ_TextAttachment *)attachment attributes:(NSDictionary *)attributes
{
    // Core Text 通过runDelegate确定非文字（attachment）区域的大小
    CTRunDelegateRef runDelegate = [LRJ_CTLayoutRun textLayoutRunWithAttachment:attachment];
    // 设置CTRunDelegateRef 和 文本颜色， 由于占位的“*”不需要显示，故设为透明色
    NSMutableDictionary *placeholderAttributes = [NSMutableDictionary dictionaryWithDictionary:attributes];
    [placeholderAttributes addEntriesFromDictionary:[NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)runDelegate, (NSString*)kCTRunDelegateAttributeName, [UIColor clearColor].CGColor,(NSString*)kCTForegroundColorAttributeName, attachment, LRJ_TextAttachmentAttributeName, nil]];
    CFRelease(runDelegate);
    
    // 所有表情文本（如“[哈哈]”）替换为一个占位符，并通过CTRunDelegateRef控制大小
    NSString *str = LRJ_TextAttachmentReplacementCharacter;
    NSAttributedString *result = [[[self class] alloc] initWithString:str attributes:placeholderAttributes];
    
    return result;
}

@end




